package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class VideoService {

    @Reference(version = "1.0.0")
    private VideoApi videoApi;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private QuanZiService quanZiService;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private VideoMQService videoMQService;

    //发布小视频
    public boolean saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        try {

            User user = UserThreadLocal.get();

            Video video = new Video();
            video.setUserId(user.getId());
            video.setSeeType(1);//权限默认为公开

            //上传图片
            PicUploadResult picUploadResult = picUploadService.upload(picFile);
            video.setPicUrl(picUploadResult.getName());

            //上传视频

            StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(),
                    StrUtil.subAfter(videoFile.getOriginalFilename(), '.', true),
                    null);

            //设置视频路径
            video.setVideoUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());

            String videoId = videoApi.saveVideo(video);
            if(StrUtil.isNotEmpty(videoId)){
                //发送消息
                videoMQService.videoMsg(videoId);
            }
            return StrUtil.isNotEmpty(videoId);
        }catch (Exception e){
            log.error("发布视频失败 file = " +picFile.getOriginalFilename(),e);
        }

        return false;
    }


    public PageResult queryVideoList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        User user = UserThreadLocal.get();

        PageInfo<Video> pageInfo = videoApi.queryVideoList(user.getId(), page, pageSize);
        List<Video> videoList = pageInfo.getRecords();

        if(CollUtil.isEmpty(videoList)){
            return pageResult;
        }

        //通过video的集合获取所有的userId 再通过userId查询用户信息
        List<Object> userIds = CollUtil.getFieldValues(videoList, "userId");
        List<UserInfo> userInfoList = userInfoService.queryUserInfoListByUserIdList(userIds);

        List<VideoVo> videoVoList = new ArrayList<>();
        for (Video video : videoList) {
            VideoVo videoVo = new VideoVo();

            videoVo.setUserId(video.getUserId());
            videoVo.setCover(video.getPicUrl());
            videoVo.setVideoUrl(video.getVideoUrl());
            videoVo.setId(video.getId().toHexString());
            videoVo.setSignature("hello mother fuck"); //TODO 签名

            videoVo.setCommentCount(Convert.toInt(quanZiApi.queryCommentsCount(videoVo.getId()))); //评论数
            videoVo.setHasFocus(videoApi.isFollowUser(user.getId(),videoVo.getUserId()) ? 1 : 0); // 是否关注 (1是 ， 0 否)
            videoVo.setHasLiked(quanZiApi.queryUserIsLike(user.getId(),videoVo.getId()) ? 1 : 0); // 是否点赞（1是，0否）
            videoVo.setLikeCount(Convert.toInt(quanZiApi.queryLikeCount(videoVo.getId())));// 点赞数

            //填充用户信息
            for (UserInfo userInfo : userInfoList) {
                if(ObjectUtil.equals(videoVo.getUserId(), userInfo.getUserId())){
                    videoVo.setNickname(userInfo.getNickName());
                    videoVo.setAvatar(userInfo.getLogo());
                    break;
                }
            }
            videoVoList.add(videoVo);
        }

        pageResult.setItems(videoVoList);

        return pageResult;
    }


    public Long likeComment(String videoId) {
        User user = UserThreadLocal.get();
        Boolean bool = quanZiApi.likeComment(user.getId(), videoId);
        if (bool){
            //发送消息
            videoMQService.likeVideoMsg(videoId);
            return quanZiApi.queryLikeCount(videoId);
        }

        return null;
    }

    public Long disLikeComment(String videoId) {
        User user = UserThreadLocal.get();
        Boolean bool = quanZiApi.disLikeComment(user.getId(), videoId);
        if (bool){
            videoMQService.disLikeVideoMsg(videoId);
            return quanZiApi.queryLikeCount(videoId);
        }
        return null;
    }

    public PageResult queryCommentList(String videoId, Integer page, Integer pageSize) {
        return quanZiService.queryCommentList(videoId,page,pageSize);
    }


    public Boolean saveComment(String videoId, String comment) {
        Boolean bool = quanZiService.saveComments(videoId, comment);
        if(bool){
            //发送消息
            videoMQService.commentVideoMsg(videoId);
        }
        return bool;
    }

    public Boolean followUser(Long followUserId) {
        User user = UserThreadLocal.get();
        return videoApi.followUser(user.getId(),followUserId);
    }

    public boolean disFollowUser(Long followUserId) {
        User user  = UserThreadLocal.get();
        return videoApi.disFollowUser(user.getId(),followUserId);
    }
}
